'use strict'

const Service = require('egg').Service;
const randomstring= require('randomstring');
class RoomService extends Service {
  /**
   * 创建群组
   * @param {*} param0 
   */
  async createRoom({ userIds }) {
    const list = userIds.split(',');
    const name = "测试群组";
    const roomId = randomstring.generate(12);

    const sql = `
      insert
        into t_chat_room (room_name, room_id, room_owner)
        values('${name}', '${roomId}', ${1})
      `;
    await this.app.mysql.query(sql);

    list.push(1)

    const room = (await this.app.mysql.query(`select * from t_chat_room where room_name = '${name}'`))[0];
    for(let i = 0; i < list.length; i++) {
      await this.app.mysql.query(`insert into t_chat_room_to_user (user_id, room_id) values(${list[i]}, ${room.id})`);
    }

    return room;
  }

  /**
   * 获取房间列表
   * @returns 
   */
  async getRoomList() {
    const list = this.app.mysql.query(`select * from t_chat_room`);
    return list;
  }

  /**
   * 获取群组的用户列表
   * @param {*} param0 
   * @returns 
   */
  async getRoomUserList({ roomId }) {
    const sql = `
      select
        *
      from
        t_chat_room_to_user t
      left join
        t_user
      on
        t.user_id = t_user.id
      where
        t.room_id = '${roomId}'
    `
    const list = this.app.mysql.query(sql);
    return list;
  }

  /**
   * 获取群组的用户列表
   * @param {*} param0 
   * @returns 
   */
  async getRoomUserListByKey({ roomId }) {
    const rooms = await this.app.mysql.query(`select * from t_chat_room where room_key = '${roomId}'`);
    const sql = `
      select
        *
      from
        t_chat_room_to_user t
      left join
        t_user
      on
        t.user_id = t_user.id
      where
        t.room_id = ${rooms[0].id}
    `
    const list = this.app.mysql.query(sql);
    return list;
  }
}

module.exports = RoomService;
